using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class ListView : MonoBehaviour
{
    #region 嵌套的Item类
    public class ListViewItem : MonoBehaviour, IPointerClickHandler
    {
        public ListView owner;  // Item类需要一个作为拥有者的View

        #region 被选中的bool及其属性，被选中时会执行选中方法
        private bool selected;
        public bool Selected
        {
            get { return selected; }
            set
            {
                selected = value;
                onSelected(selected);
            }
        }
        #endregion

        #region 选中方法
        public virtual void onSelected(bool selected)
        {
            // 主要用来被子类重写为切换高亮状态
        }

        public void OnPointerClick(PointerEventData eventData)
        {
            if (!this.selected)
            {
                this.Selected = true;
            }
            if (owner != null && owner.SelectedItem != this)
            {
                owner.SelectedItem = this;
            }
        }
        #endregion

    }
    #endregion

    public UnityAction<ListViewItem> onItemSelected;    // 定义一个参数为Item的事件，当有新Item被选中时触发

    List<ListViewItem> items = new List<ListViewItem>();    // 获取View下的所有Item

    #region View标记选中的Item的属性
    private ListViewItem selectedItem = null;
    public ListViewItem SelectedItem
    {
        get { return selectedItem; }
        private set
        {
            if (selectedItem != null && selectedItem != value)    // 将原来的Item的选中状态取消
            {
                selectedItem.Selected = false;
            }

            selectedItem = value;       // 获取新的被选中的Item

            if (onItemSelected != null)         // 选中新的Item时触发事件
                onItemSelected.Invoke((ListViewItem)value);
        }
    }
    #endregion


    #region 对View的Item成员进行添加与删除
    public void AddItem(ListViewItem item)
    {
        item.owner = this;
        this.items.Add(item);
    }

    public void RemoveAll()
    {
        foreach (var it in items)
        {
            Destroy(it.gameObject);
        }
        items.Clear();
    }
    #endregion

}
